package com.lzw.mall.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.AlipayUtils;
import com.lzw.mall.common.config.AliPayConfigBean;
import com.lzw.mall.common.entity.Orders;
import com.lzw.mall.common.service.IOrdersService;
import com.lzw.mall.common.service.IPayService;
import com.lzw.mall.common.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/order")
@Controller
public class OrderController {

    @Autowired
    private IOrdersService orderService;

    @Autowired
    private IPayService payService;

    @Autowired
    private AliPayConfigBean aliPayConfigBean;



    @PostMapping("/save")
    public String save(String ids, Integer addId, Model model){//ids是cart表中的id，addId是用户地址档案的ID
        //生成订单
        Map<String,Object> map=orderService.saveOrder(ids, addId);
        //String qrcode=orderService.saveOrder(ids, addId);
        model.addAttribute("qrCode",map.get("qrCode"));
        model.addAttribute("order",map.get("order"));
        model.addAttribute("orderAddress",map.get("orderAddress"));

        return "payment";
    }

    @PostMapping("/notify")
    @ResponseBody
    public String notify(HttpServletRequest request){
        /*Map<String, String> params=new HashMap<>();
        Map<String, String[]> requestParams=request.getParameterMap();
        for (String name: requestParams.keySet()){
            String[] values = requestParams.get(name);
            String valueStr="";
            for(int i = 0; i < values.length; i++){
                valueStr =(i ==values.length - 1) ? valueStr+values[i] :valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        System.out.println(params);
        //验证信息签名是否正确
        boolean signVerified =AliPayUtil.verify(params);

        if (signVerified) {
            if(params.get("trade_status").equals("TRADE_SUCCESS")){
                String tradeNo=params.get("trade_no");
                //记录回调信息
                payService.payResult(params);
                //修改本订单的状态
                orderService.doUpdateStatus(params.get("out_trade_no"),"待发货");
            }
        }*/

        //获取支付宝POST过来反馈信息，将异步通知中收到的待验证所有参数都存放到map中
        Map< String , String > params = new HashMap < String , String > ();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String [])requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i ++ ){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put (name,valueStr);
        }
//调用SDK验证签名
//公钥验签示例代码
        boolean  signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfigBean.getPublicKey(), "UTF-8",aliPayConfigBean.getSignType());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
//公钥证书验签示例代码
//   boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");

        if (signVerified){
            // TODO 验签成功后
            //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success
            //记录回调信息
            payService.payResult(params);
            //修改本订单的状态
            orderService.doUpdateStatus(params.get("out_trade_no"),"待发货");
            return "success";
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回fail.
            return "fail";
        }

    }

    @JmsListener(destination = "order.save")
    public void orderCheck(Integer id){
        System.out.println(new Date()+"订单id是："+id);
    }

    @GetMapping("/payStatus")
    @ResponseBody
    public String payStatus(Integer id){
        Orders order =orderService.getById(id);
        System.out.println(id);
        System.out.println(order);
        return order.getStatus();
    }


    @GetMapping("/selectOrderList")
    @ResponseBody
    public List<OrderVO> selectOrderList(String status){
        return orderService.selectOrderList(status);
    }


}
